<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app'
import { ref, provide, nextTick, computed } from 'vue'
import insureJ from './components/insure-j.vue'
import { getFile } from '@/api/common/index'
import FilterNavbar from '@/components/FilterNavbar'
import { addApi, editApi, getDetailApi } from '@/api/asset/car-insure'
import { getCarDetail } from '@/api/asset/car-manager'
import CarInfo from '../detail/components/carInfo.vue'
import useFormFold from '@/hooks/useFormFold'
import { useLoadDataAndHotUpdateNavigateBack } from '@/hooks/useListNavigate'
// import { usePageDict, useSysDict } from '@/hooks/useDict'
// import { getListApi } from '@/api/asset/car-maintenance'

// const dict = usePageDict('shortOrderDict')
// const sysDict = useSysDict(['equipment_brand', 'connection_mode'])

const initFold1 = ref(true)
const pageTitle = ref('保险')
const record = ref({})
const pageType = ref(null)
const insureKind = ref(0)  //0交强险  1商业性
const form = ref({
  carId: '',
  insureAddList:[
    {
      index: 0,
      insureCompany: '',
      initFold: true,
      insureKind: insureKind.value,  //0交强险  1商业性
      times: [], //默认给[]
      insuredSum: null,
      insureAmt: null,
      policyImgFileId: null,
      carInsureDetail: [
        {
          insureKindType: null,
          insuredSum: null,
          insureAmt: null
        }
      ],
      siteId:'',
      siteName:'',
    }
  ]
})
provide('form', form)

const { foldStatus, foldValidate } = useFormFold([
  {
    key: 'fold1',
    props: ['licenseNo'],
  },
])

const rules = computed(() => {
  const _rules: any = {}
  form.value.insureAddList.forEach((item: any, index: number) => {
    _rules[`insureAddList.${index}.insureCompany`] = {
      required: true,
      message: '请选择',
    }
    _rules[`insureAddList.${index}.siteId`] = {
      required: true,
      message: '请选择',
    }
    _rules[`insureAddList.${index}.times`] = {
      type: 'array',
      min: 2,
      required: true,
      message: '请选择',
    }
  })
  _rules['licenseNo'] = {
    required: true,
    message: '请选择'
  }
  return _rules
})
// 选择车牌号
const changeLicenseNo = (a, option = {}) => {
  form.value.carId = a
  form.value.licenseNo = option.licenseNo
  form.value.siteId = option.siteId
  form.value.siteName = option.siteName
  record.value = option
  changeInsure()
}
const getInsureDetail = async (id) => {
  var res = await getDetailApi({id:id})
  var r = res.result
  // 为了复用页面,需要将数据格式统一为新增时,编辑提交时再处理回原格式
  form.value.id = r.id
  // 车辆start
  form.value.carId = r.carId
  form.value.licenseNo = r.licenseNo
  form.value.modelName = r.modelName
  form.value.siteName = r.siteName
  form.value.libraryName = r.libraryName
  form.value.vin = r.vin
  form.value.insureStatusStr = r.insureStatusStr
  // 车辆end
  form.value.insureAddList = [
    {
      siteId: r.siteId,
      siteName: r.siteName,
      insureCompany: r.insureCompany,
      insureCompanyStr: r.insureCompanyStr,
      insureNo: r.insureNo,
      insureKind: r.insureKind,
      beginDate: r.beginDate,
      endDate: r.endDate,
      times: [r.beginDate, r.endDate],
      insuredSum: r.insuredSum,
      insureAmt: r.insureAmt,
      policyImgFileId: r.policyImgFileId, //保险单附件
      carInsureDetail: r.carInsureDetail, //商业险险种
      fileObj: r.policyImgFileId?getFile({idList: [r.policyImgFileId]}).then((res) => {
        console.log('res', res)
        if (res.code == 200) {
          return {
            fileIdStr: res.result.fileIdStr,
            fileName: res.result.originalFileName,
            openUrl: res.result.openUrl,
          }
        }
      }):undefined,
    }
  ]
  console.log('详情form', form.value)
}
const changesupplierMainId = (a, option = {}) => {
  form.value.maintenanceShopId = a
  form.value.maintenanceShop = option.supplierName
}
// 新增
const addInsure = () => {
  console.log('类型', insureKind.value)
  if(form.value.insureAddList.length > 5){
    uni.showToast({
      icon: 'none',
      title: '最多添加5条'
    })
    return false
  }
  // nextTick(()=>{
  form.value.insureAddList.push({
    index: form.value.insureAddList.length,
    initFold: true,
    insureKind: insureKind.value,  //0交强险  1商业性
    times: [], //添加时默认给[]
    policyImgFileId: null,
    carInsureDetail: [
      {
        insureKindType: null,
        insuredSum: null,
        insureAmt: null
      }
    ],
    siteId:form.value.siteId,
    siteName:form.value.siteName,
  })
  // })
  console.log(form.value)
}
const changeInsure = () => {
    form.value.insureAddList.forEach((item: any, index: number) => {
      item.siteId = form.value.siteId
      item.siteName = form.value.siteName
    })
  }
// 首页快捷跳转,获取车辆信息
const pagefrom = ref(null) //是否是首页来的
const getCarInfo = (carId) => {
  getCarDetail({id: carId}).then((res)=>{
    var car = res.result
    form.value.carId = car.id
    form.value.licenseNo = car.licenseNo
    form.value.siteId = car.siteId
    form.value.siteName = car.siteName
    changeInsure()
    record.value.licenseNo = car.licenseNo
    record.value.vin = car.vin
    record.value.modelName = car.modelName
    record.value.siteName = car.siteName
    record.value.libraryName = car.libraryName
  })
}
onLoad((options)=>{
  console.log('options', options)
  pageType.value = options.pageType
  insureKind.value = Number(options.insure)
  // if(options.id){
  //   // getDetail(options.id)
  // }
  if(insureKind.value == 0 && pageType.value == 'add'){
    pageTitle.value = '新增交强险'
    form.value.insureAddList[0].insureKind = 0
    // 首页即将到期新增
    if(options.carId){
      pagefrom.value = options.pagefrom
      getCarInfo(options.carId)
    }
  }
  if(insureKind.value == 1 && pageType.value == 'add'){
    pageTitle.value = '新增商业险'
    form.value.insureAddList[0].insureKind = 1
    // 首页即将到期新增
    if(options.carId){
      pagefrom.value = options.pagefrom
      getCarInfo(options.carId)
    }
  }
  if(insureKind.value == 0 && pageType.value == 'edit'){
    pageTitle.value = '编辑交强险'
    form.value.insureAddList[0].insureKind = 0
    getInsureDetail(options.insureId)
  }
  if(insureKind.value == 1 && pageType.value == 'edit'){
    pageTitle.value = '编辑商业险'
    form.value.insureAddList[0].insureKind = 1
    getInsureDetail(options.insureId)
  }
  pagefrom.value = options.pagefrom
  console.log('form.value', form.value)
  // uni.setNavigationBarTitle({
  //   title: pageTitle.value
  // })
})
defineExpose({
  // getMainLists,
  // updateCarInfo,
})

const ve_form = ref(null)
const formSubmit = () => {
  console.log(form.value)
  ve_form.value.validate((valid, errors) => {
    console.log(valid)
    if (valid) {
      var params = {
        ...form.value
      }
      if(pageType.value == 'add'){
        params.insureKind = insureKind.value
        addApi(params).then((res)=>{
          console.log(res)
          if(res.code == 200){
            // 车辆管理列表新增成功后，跳转至保险列表
            if (pageFrom.value == 'carManagerList') {
              // 1 商业险 0 交强险
              uni.redirectTo({
                url: `/pages/asset/car-manager/detail/${insureKind.value == 1 ? 'business-insure-info' : 'jq-insure-info'}?id=${form.value.carId}`,
              })
            } else {
              useLoadDataAndHotUpdateNavigateBack()
            }
          }else{
            uni.showToast({
              icon: 'none',
              title: res.message
            })
            return false
          }
        })
      }
      if(pageType.value == 'edit'){
        var insureAddList = form.value.insureAddList[0]
        // 编辑时需要提交的数据格式
        var newParams = {
          carId: form.value.carId,
          id: form.value.id,
          insureNo: insureAddList.insureNo,
          insureCompany: insureAddList.insureCompany,
          beginDate: insureAddList.times[0],
          endDate: insureAddList.times[1],
          policyImgFileId: insureAddList.policyImgFileId,
          insuredSum: insureAddList.insuredSum,
          insureAmt: insureAddList.insureAmt,
          carInsureDetail: insureAddList.carInsureDetail, //商业险多险种
          insureKind: insureKind.value,
          siteId: insureAddList.siteId,
        }
        editApi(newParams).then((res)=>{
          console.log(res)
          if(res.code == 200){
            useLoadDataAndHotUpdateNavigateBack()
          }else{
            uni.showToast({
              icon: 'none',
              title: res.message
            })
            return false
          }
        })
      }
    }
  })
}

</script>

<template>
  <view class="container">
    <FilterNavbar>
      <template #center>
        <view class="navbar-title"> {{ pageTitle }} </view>
      </template>
    </FilterNavbar>
    <ve-form style="padding: 24rpx;" ref="ve_form" :model="form" :rules="rules">
      <ve-card title="车辆基本信息" type="none" fold v-model:initFold="foldStatus.fold1">
        <ve-form-item label="车牌号" :borderBottom="false" prop="licenseNo" required>
          <ve-input v-if="pageType != 'add' || pagefrom == 'home'" v-model="form.licenseNo" disabled :allowClear="false" />
          <remote-select v-else type="licenseNo" :label="form.licenseNo" v-model="form.carId" :params="{ idList: form.carId ? [form.carId] : undefined }" @change="changeLicenseNo" />
        </ve-form-item>
        <car-info v-if="record.licenseNo" :record="record" :pageType="pageType" />
        <view :style="record.licenseNo?'height: 24rpx;':''"></view>
      </ve-card>
      <insureJ :pageType="pageType"></insureJ>
      <view class="ve-form-item-btn" @click="addInsure" v-if="pageType=='add'">
        <ve-icon name="plus" size="30"></ve-icon>
        <span class="ve-form-item-btn-text">{{form.insureAddList[0].insureKind == 0 ? '新增交强险': '新增商业险'}}</span>
      </view>
    </ve-form>
    <ve-bottom-box>
      <ve-button type="primary" @click="formSubmit" style="width: 100%;">确认</ve-button>
    </ve-bottom-box>
  </view>
</template>

<style lang="scss" scoped>
.container {
  background: #F7F8FA;
}
.car-info-content {
  background: #f7f8fa;
  border-radius: 0rpx 0rpx 0rpx 0rpx;
  opacity: 1;
  box-sizing: border-box;
  padding: 24rpx;
}
:deep(.ve-form-item__body__left){
  margin-bottom: 0 !important;
}
:deep(.upload){
  margin-top: 0 !important;
}
.ve-form-item-btn {
    margin-bottom: 20rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 88rpx;
    background: #f3f7ff;
    border-radius: 4rpx 4rpx 4rpx 4rpx;
    opacity: 1;
    border: 2rpx solid #3072f6;
    .ve-form-item-btn-text {
      font-size: 30rpx;
      font-family: PingFang SC-Regular, PingFang SC;
      font-weight: 400;
      color: #3072f6;
      margin-left: 18rpx;
    }
  }
.car-info-content {
  height: 168rpx;
  background-image: url('../../../../static/images/carinfo-bc.png');
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
  display: flex;
  flex-direction: column;
  align-items: self-start;
  justify-content: center;
  padding-left: 32rpx;
  color: #ffffff;
  font-family: PingFang SC-Regular, PingFang SC;

  view:nth-of-type(1) {
    font-size: 40rpx;
    font-weight: 600;
    margin-bottom: 4rpx;
  }
  view:nth-of-type(2) {
    margin-top: 4rpx;
    font-size: 28rpx;
    font-weight: 400;
  }
}
:deep(.ve-card-content){
  padding-top: 0;
  padding-bottom: 0;
}
</style>
